import os
import subprocess
import sys

def convert_to_pdf(input_dir):
    extensions = ('.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx')
    success = 0
    failures = []

    for root, _, files in os.walk(input_dir):
        for file in files:
            if file.lower().endswith(extensions):
                file_path = os.path.join(root, file)
                output_dir = os.path.join(root, 'pdf')
                os.makedirs(output_dir, exist_ok=True)
                
                try:
                    subprocess.run([
                        r'C:\Program Files\LibreOffice\program\soffice.exe',
                        '--headless',
                        '--convert-to', 'pdf',
                        '--outdir', output_dir,
                        file_path
                    ], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
                    success += 1
                except Exception as e:
                    failures.append(f'{file_path} ({str(e)})')

    print(f'转换完成！成功：{success}个，失败：{len(failures)}个')
    if failures:
        print('\n失败文件：')
        for f in failures:
            print(f' - {f}')

if __name__ == '__main__':
    input_dir = input('请输入要转换的目录路径：').strip()
    if not os.path.isdir(input_dir):
        print('错误：目录不存在')
        sys.exit(1)
    convert_to_pdf(input_dir)